// PDF.js 配置工具
export const configurePDFJS = async () => {
  try {

    // 动态导入 PDF.js
    const pdfjsLib = await import('pdfjs-dist')

    // 配置 Worker - 使用本地文件
    if (pdfjsLib.GlobalWorkerOptions) {
      pdfjsLib.GlobalWorkerOptions.workerSrc = '/pdf.worker.min.js'

    } else {

    }
    
    // 获取 PDF.js API
    let PDFJS = null
    if (pdfjsLib.getDocument) {
      PDFJS = pdfjsLib

    } else if (pdfjsLib.default && pdfjsLib.default.getDocument) {
      PDFJS = pdfjsLib.default

    } else {
      throw new Error('无法找到 PDF.js getDocument 方法')
    }
    
    // 验证 Worker 文件是否可访问
    try {
      const workerResponse = await fetch('/pdf.worker.min.js')
      if (workerResponse.ok) {

      } else {

      }
    } catch (fetchError) {

    }
    
    return {
      success: true,
      pdfjs: PDFJS,
      workerSrc: pdfjsLib.GlobalWorkerOptions?.workerSrc
    }
  } catch (error) {

    return {
      success: false,
      error: error.message
    }
  }
}

// 测试 PDF 加载功能
export const testPDFLoad = async (pdfUrl) => {
  try {

    const config = await configurePDFJS()
    if (!config.success) {
      throw new Error('PDF.js 配置失败: ' + config.error)
    }
    
    const PDFJS = config.pdfjs
    const loadingTask = PDFJS.getDocument(pdfUrl)
    const pdf = await loadingTask.promise

    return {
      success: true,
      pdf: pdf,
      numPages: pdf.numPages
    }
  } catch (error) {

    return {
      success: false,
      error: error.message
    }
  }
}
